
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "MyHoughLines.h"
#include "MyCanny.h"
using namespace std;
using namespace cv;

int main()
{
    cv::Mat img = cv::imread("/home/lin/桌面/test.jpeg");
    // cv::Mat img = cv::imread("/home/lin/图片/007.png");
    cv::resize(img,img,cv::Size(640,480));
    cv::Mat gray_img;
    cv::cvtColor(img,gray_img,cv::COLOR_BGR2GRAY);
    //canny
    cv::Mat dstImage, edge;
    cv::blur(gray_img, gray_img, Size(3,3));
    // dip::Canny(gray_img,edge,100,150);
    cv::Canny(gray_img, edge, 150, 100, 3);
 
    // dstImage.create(srcImage1.size(), srcImage1.type());
    // dstImage = Scalar::all(0);
    // srcImage1.copyTo(dstImage, edge);
    //Hough
    cv::Mat line_img;
    img.copyTo(line_img);
    vector<cv::Vec2f> lines;            //定义一个矢量结构用于存放得到的线段矢量集合
    dip::HoughLines(edge,lines,180);
	// cv::HoughLines(edge, lines, 1, CV_PI / 180, 180, 0, 0);
    //rho, theta, threshold
    std::cout<<"lines size:"<<lines.size()<<std::endl;
	for (size_t i = 0; i < lines.size(); i++)
	{
		
        float rho = lines[i][0];
		float theta = lines[i][1];
		// std::cout<<"i:"<<i<<",rho:"<<rho<<","<<theta<<std::endl;
        Point pt1, pt2;
		double a = cos(theta), b = sin(theta);
		double x0 = a * rho, y0 = b * rho;
		pt1.x = cvRound(x0 + 1000 * (-b));
		pt1.y = cvRound(y0 + 1000 * (a));
		pt2.x = cvRound(x0 - 1000 * (-b));
		pt2.y = cvRound(y0 - 1000 * (a));
		line(line_img, pt1, pt2, Scalar(0, 0, 255), 1, LINE_AA);
    }

    cv::Mat circle_img;
    img.copyTo(circle_img);

	int minDist = img.rows / 8;
	int param1 = 100;
	int param2 = 50;//圆心阈值
	vector<Vec3f> circles;
    // dip::HoughCircle(edge,circles,10,200,10);
    HoughCircles(gray_img, circles, cv::HOUGH_GRADIENT, 1, minDist, param1, param2, 5,200);
    //绘制检测到的圆
    std::cout<<"circle nums:"<<circles.size()<<std::endl;
	for (size_t i = 0; i < circles.size(); i++)
	{
		std::cout<<"x,y,r:"<<circles[i][0]<<","<<circles[i][1]<<","<<circles[i][2]<<std::endl;
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
		int radius = cvRound(circles[i][2]);
		circle(circle_img, center, 3, Scalar(0, 0, 255), -1, 8, 0);
		circle(circle_img, center, radius, Scalar(0, 0, 255), 3, 8, 0);
	}

    while (true)
    {
        cv::imshow("gray",gray_img);
        cv::imshow("canny",edge);
        cv::imshow("lines",line_img);
        cv::imshow("circle",circle_img);
        char q = cv::waitKey(10);
        if (q==27){
            break;
        }
    }
    cv::destroyAllWindows();


}